package cn.schoolwow.workflow.module.task.action.flow.complete.nodeType.gateway.common;

import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickdao.domain.database.dql.subCondition.SubCondition;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.domain.deploy.DeployNodeType;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.entity.WorkFlowNode;
import cn.schoolwow.workflow.entity.WorkFlowNodeJump;
import cn.schoolwow.workflow.entity.WorkFlowTask;
import cn.schoolwow.workflow.module.task.action.flow.common.AutomaticPassNodeCommonFlow;

import java.util.List;

public class CompleteGatewayEndNodeCommonFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String gatewayNodeTypeName = flowContext.checkData("gatewayNodeTypeName", String.class);
        WorkFlowNode gatewayNode = flowContext.checkData("gatewayNode", WorkFlowNode.class);
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        //判断网关节点节点的前驱节点列表,查询其中审批节点，若全部已完成，则继续向后执行,否则结束
        Condition condition = transaction.query(WorkFlowTask.class)
                .addColumn("complete")
                .addQuery("instanceId", workFlowInstance.getId());

        SubCondition workFlowNodeSubCondition = condition.joinTable(WorkFlowNode.class,"nodeId", "id")
                .addQuery("type", DeployNodeType.AuditNode.value);

        SubCondition workFlowNodeJumpSubCondition = workFlowNodeSubCondition.joinTable(WorkFlowNodeJump.class,"id", "currentNodeId")
                .addQuery("definitionId", gatewayNode.getDefinitionId())
                .addQuery("nextNodeId", gatewayNode.getId());

        List<Boolean> completeList = condition.execute().getSingleColumnList(Boolean.class);

        if(completeList.isEmpty()){
            throw new IllegalArgumentException(gatewayNodeTypeName+"["+gatewayNode.getName()+"]没有前驱节点列表!");
        }
        int count = 0;
        for(Boolean complete:completeList){
            if(null!=complete&&complete){
                count++;
            }
        }
        if(count<completeList.size()){
            flowContext.brokenCurrentFlow(gatewayNodeTypeName+"前驱节点中存在未完成节点");
        }
        flowContext.startFlow(new AutomaticPassNodeCommonFlow())
                .putCurrentCompositeFlowData("passNode", gatewayNode)
                .execute();
    }

    @Override
    public String name() {
        return "完成网关结束位置节点公共流程";
    }
}
